import axios from 'axios'
import qs from 'qs'
import router from '../router'
import storage from './store'

let baseConfig = {
    baseUrl:'',
    timeout:10000
}
//创建axios实例
let instance = axios.create(baseConfig)

//配置请求拦截器
instance.interceptors.request.use(function(config){
    let uid = storage.instance.get("uid");
    if(uid){
        config.withCredentials = true // 允许携带token ,这个是解决跨域产生的相关问题
        config.headers["userid"] = uid;
        config.headers["token"] = storage.instance.get("token")
    }
    //config.data 请求体
    if(config.method == "post" || config.method == "put"){
        config.data = qs.stringify(config.data);
        config.headers["Content-Type"] = "application/x-www-form-urlencoded"
    }
    return config;
});
//响应拦截器
instance.interceptors.response.use(resp =>{
    if(resp.status == 200){
        if(resp.data.code == 401){
            //后台登录检验不通过， 跳回登录页面
            router.push("/login");
            return;
        }
        return resp.data;
    }else {
        return Promise.reject(resp.status);
    }
},
error =>{
    return Promise.reject(error)
})

let http = {
    install(app){
        app.prototype.$http = instance;
        //app.config.globalProperties.$axios = instance;  vue3的写法
    }
}

export default http;